package tk.heimashuma.store.web.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import sun.security.provider.MD5;
import tk.heimashuma.store.entity.Users;
import tk.heimashuma.store.service.UserService;
import tk.heimashuma.store.utils.GeetestConfig;
import tk.heimashuma.store.utils.GeetestLib;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;

@Controller
public class AuthController {
    @Autowired
    private GeetestLib geetestLib;
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/startCaptcha",method = {RequestMethod.GET})
    public void startCaptcha(HttpServletRequest request,
                             HttpServletResponse response,HttpSession session) throws IOException {
        String resStr = "{}";
        String userid = UUID.randomUUID().toString().replace("-","");
        session.setAttribute("verification",userid);
        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("user_id", userid); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", request.getRemoteAddr()); //传输用户请求验证时所携带的IP

        //进行验证预处理
        int gtServerStatus = geetestLib.preProcess(param);
        //将服务器状态设置到session中
        request.getSession().setAttribute(geetestLib.gtServerStatusSessionKey, gtServerStatus);
        //将userid设置到session中
        request.getSession().setAttribute("userid", userid);

        resStr = geetestLib.getResponseStr();
        PrintWriter out = response.getWriter();
        out.println(resStr);
    }
    @RequestMapping(value = "verifyLogin",method = {RequestMethod.POST})
    public @ResponseBody  String verifyLogin(Users user, HttpServletRequest request,
                       HttpServletResponse response, RedirectAttributes model,HttpSession session) throws IOException {

        String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
        String validate = request.getParameter(GeetestLib.fn_geetest_validate);
        String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
        //从session中获取gt-server状态
        int gt_server_status_code = (Integer) request.getSession().getAttribute(geetestLib.gtServerStatusSessionKey);
        //从session中获取userid
        //String userid = (String)request.getSession().getAttribute("userid");
        String userid = (String) session.getAttribute("verification");
        //自定义参数,可选择添加

        HashMap<String, String> param = new HashMap<String, String>();
        param.put("user_id", userid); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", request.getRemoteAddr()); //传输用户请求验证时所携带的IP
        int gtResult = 0;
        if (gt_server_status_code == 1) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = geetestLib.enhencedValidateRequest(challenge, validate, seccode, param);
        } else {
            // gt-server非正常情况下，进行failback模式验证
            gtResult = geetestLib.failbackValidateRequest(challenge, validate, seccode);
        }
        if (gtResult == 1) {
            // 验证数据成功
            return "yes";
        }
        else {
            // 验证数据失败
            return "no";
        }
    }
}
